﻿using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.ComponentModel;
using System.Device.Location;
using System.IO.IsolatedStorage;
using System.Windows;
using AuchanScan.Datas;
using AuchanScan.Services;

namespace AuchanScan.ViewModels
{
    public class GeoViewModel : INotifyPropertyChanged
    {
        public GeoViewModel()
        {
            if (IsolatedStorageSettings.ApplicationSettings.Contains("MapLng") &&
                IsolatedStorageSettings.ApplicationSettings.Contains("MapLat"))
                CenterMap = new GeoCoordinate
                    {
                        Longitude = (double) IsolatedStorageSettings.ApplicationSettings["MapLng"],
                        Latitude = (double) IsolatedStorageSettings.ApplicationSettings["MapLat"]
                    };
            else
                CenterMap = new GeoCoordinate { Latitude = 48.858333, Longitude = 2.294444 };

            Places = new ObservableCollection<Magasin>(MagasinsService.Magasins);
        }

        public ObservableCollection<Magasin> Places { get; set; }

        public bool DisplayMsgBoxWhenLeaving { get; set; }

        public GeoCoordinate CenterMap { get; set; }
        public bool LoadingPlaces { get; set; }
        public List<String> Suggestions { get; set; }

        #region INotifyPropertyChanged Members

        public event PropertyChangedEventHandler PropertyChanged;

        #endregion

        public String DistanceDisplay(double distance)
        {
            if (distance < 1)
                return ((int) (distance*100)) + "m";
            else
                return distance.ToString("#.0") + "km";
        }

        public void SetLoading(bool val)
        {
            LoadingPlaces = val;
            RaisePropertyChanged("LoadingPlaces");
        }

        public void ComputeCoordinate(GeoCoordinate coord)
        {
            if (coord == null)
            {
                coord = CenterMap;
            }

            Deployment.Current.Dispatcher.BeginInvoke(() =>
                {
                    CenterMap = coord;
                    RaisePropertyChanged("CenterMap");
                });
        }


        public void RaisePropertyChanged(String property)
        {
            if (PropertyChanged == null)
                return;
            PropertyChanged(this, new PropertyChangedEventArgs(property));
        }

        public void Save()
        {
            IsolatedStorageSettings.ApplicationSettings["MapLng"] = CenterMap.Longitude;
            IsolatedStorageSettings.ApplicationSettings["MapLat"] = CenterMap.Latitude;
        }
    }
}